#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <jansson.h>
#include <string.h>

#include "cmder.h"


struct tm *json_to_time(json_t *);


int main_interperter(char *query, char *url)
{
    printf("entered interperter\n");
    printf("%s\n",query);
    json_t *tmp, *jdata;
    json_error_t error;

    struct tm *start, *end;
    tmp = json_loads(query, 0, &error);
    if(tmp == NULL)
    {
        fprintf(stderr, "Loading json failed on line:%d, error:%s\n", error.line, error.text);
        return 2;
    }
    if(!json_is_array(tmp))
    {
        fprintf(stderr, "Json is not an array");
        json_decref(tmp);
        return 3;
    }
    for(int i=0;i<json_array_size(tmp);i++)
    {
        jdata = json_array_get(tmp, i);
        if(!json_is_object(jdata))
        {
            fprintf(stderr, "Objected adding failed at line %d", i);
            json_decref(tmp);
            return 4;
        }
        
    }
    start = json_to_time(json_object_get(jdata, "start"));
    end = json_to_time(json_object_get(jdata, "end"));
    if((start==NULL)||(end==NULL))
    {
        fprintf(stderr, "faild converting string to time struct\n");
        return 2;
    }
    create_entry(start, end);
    
    return 1;
}
struct tm *json_to_time(json_t *convert)
{
    if(!json_is_string(convert))
    {
        fprintf(stderr, "Provided date is not as string\n");
        return NULL;
    }
    char *sdate = (char *)json_string_value(convert);
    printf("%s\n", sdate);
    struct tm *ret = malloc(sizeof(struct tm));
    /* yyyy-mm-ddThh:mm:ss */
    char buff[5];
    memcpy(buff, sdate, 4);
    buff[4] = '\0';
    ret->tm_year = atoi(buff);
    printf("now as an integer for year %d\n", ret->tm_year);
    memcpy(buff, sdate + 5, 2);
    buff[2] ='\0';
    ret->tm_mon = atoi(buff);
    printf("now as an integer for month: %d\n", ret->tm_mon);
    memcpy(buff, sdate + 8, 2);
    buff[2] = '\0';
    ret->tm_mday = atoi(buff);
    printf("now as an integer for day: %d\n", ret->tm_mday);
    memcpy(buff, sdate + 11, 2);
    buff[2] = '\0';
    ret->tm_hour = atoi(buff);
    printf("now as an integer for hour: %d\n", ret->tm_hour);
    memcpy(buff, sdate + 14, 2);
    buff[2] = '\0';
    ret->tm_min = atoi(buff);
    printf("now as an integer for minutes: %d\n", ret->tm_min);
    return ret;
}